#include "HttpServer.hpp"
#include "Usage.hpp"
#include "Parse.hpp"

#include <memory>
#include <fstream>

#define WEBROOT "./wwwroot"
#define HOMEPAGE "/index.html"

void ProcessRoutine(int serverSock)
{
    char buff[10240];
    // 接收任务
    ssize_t ret = recv(serverSock, buff, sizeof(buff) - 1, 0);
    if(ret > 0)
    {
        buff[ret] = 0;
        std::cout << buff << std::endl << "--------------" << std::endl;
    }

    // 执行任务并回应
    std::vector<std::string> vs;
    Parse(buff, "\r\n", vs);

    std::vector<std::string> firstLine;
    Parse(vs[0], " ", firstLine);

    std::string path = WEBROOT;

    if(firstLine[1] == "/")
    { // ./wwwroot + /index.html
        path += HOMEPAGE;
    }
    else
    { // ./wwwroot + /a/b
        path += firstLine[1];
    }

    std::string content;
    std::ifstream ifile(path);
    if(ifile.is_open())
    {
        std::string line;
        while(std::getline(ifile, line))
        {
            content += line;
        }
        ifile.close();
    }

    std::string httpResponse;
    // 状态行
    if(content == "")
    {
        // httpResponse = "HTTP/1.1 404 NotFound\r\n";
        // httpResponse = "HTTP/1.1 302 Found\r\n";
        httpResponse = "HTTP/1.1 301 Move Permanently\r\n";
        httpResponse += "Location: ./404.html\r\n";
    }
    else
    {
        httpResponse = "HTTP/1.1 200 OK\r\n";
        httpResponse += "Content-Type: text/html\r\n";
        httpResponse += "Set-Cookie: 这是一个Cookie\r\n";
        httpResponse += "Content-Length: " + std::to_string(content.size()) + "\r\n";
    }

    // 报头不给
    // 空行
    httpResponse += "\r\n";

    // 正文
    httpResponse += content;

    // 发送回去
    send(serverSock, httpResponse.c_str(), httpResponse.size(), 0);

    // for(auto &str : vs)
    // {
    //     std::cout << "-----" << str << std::endl;
    // }

    
    // // 执行任务并回应
    // // 状态行
    // std::string httpResponse = "HTTP/1.1 200 OK\r\n";
    // // 报头不给
    // // 空行
    // httpResponse += "\r\n";
    // // 正文
    // httpResponse += "<html><h1>this is a test!</h1></html>";

    // // 发送回去
    // send(serverSock, httpResponse.c_str(), httpResponse.size(), 0);
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::unique_ptr<HttpServer> httpServer(new HttpServer(atoi(argv[1]), ProcessRoutine));
    httpServer->Start();

    return 0;
}
